//
//  YZMMYTackViewController.m
//  YZMicroStock
//
//  Created by apple on 16/11/2.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMMYTackViewController.h"
#import "YZMAlertView.h"
#import "XYPopView.h"
#import "YZMConfirminforViewController.h"
#import "YZClient.h"
#import "YZGeneralResultModel.h"
#import "YZMMyStackModel.h"
#import "NSNumber+Utils.h"
#import "YZMStockViewController.h"
#import "YZMConfigureService.h"
#import "YZMTradeTypeDef.h"
#import "YZMSeparatorCell.h"
#import "YZMDelayCharge.h"

@interface YZMMYTackViewController ()<UITableViewDelegate,UITableViewDataSource,XYPopViewDelegate, UITextFieldDelegate>

@property (nonatomic, strong) UITableView *listView;
@property (nonatomic, strong ) NSArray *datasource;
@property (nonatomic, strong) NSArray *timeDatasource;
@property (nonatomic, strong) YZMMyStackModel *model;
@property (nonatomic, assign) NSInteger addMoney;
@property (nonatomic, strong) YZMConfigureService *service;
@property (nonatomic, assign) double bonds;
@property (nonatomic, assign) double diffBalance;
@property (nonatomic, assign) BOOL addMoneyFlag;

@end

@implementation YZMMYTackViewController
{
    UILabel *myMoneyLabel;
    UILabel *allMoney;
    UILabel *ensureMoney;
    UILabel *deferMoney;
    UILabel *togetherMoney;
    UILabel *currentMoney;
    UILabel *haltMoney;
    UILabel *timeLabel;
    YZMAlertView *changeDeferalertview;
    XYPopView *popView;
}

+ (instancetype)createWithParams: (NSDictionary *)params
{
    
    YZMMYTackViewController *ctrl = [[self alloc] init];
    ctrl.isHiddenTableViewCell = params[@"isHidden"];
    return ctrl;
}

- (id)init {
    if (self = [super init]) {
        
        self.title = @"我的策略组";
        self.hidesBottomBarWhenPushed = YES;
        self.addMoney = 10000;
        self.service = [YZMConfigureService sharedServiceWithTradeType:YZM_TRADE_TYPE_FOR_A_STOCK_D];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    if (!self.isHiddenTableViewCell) {
        _datasource = @[
                        @{@"titleName" : @"当前持仓", YZNEXTPAGE : @"currentthing"},
                        @{@"titleName" : @"交易记录",  YZNEXTPAGE : @"balance"},
                        @{@"titleName" : @"历史策略组", YZNEXTPAGE : @"history"}];
    }
    [self createObject];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:YES];
    [[YZMTDConfigureService sharedService] fetchConfigureDataSuccess:nil failure:nil];
    [self getinformation];
}

-(void)createObject
{
    WS(ws)
    self.listView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
    _listView.backgroundColor=[YZMAppStyle appBackgroundColor];
    _listView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [_listView registerClass:[YZMSeparatorCell class] forCellReuseIdentifier:@"cell"];
    _listView.bounces = NO;
    [self.view addSubview:_listView];
    [_listView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(ws.view);
    }];
    _listView.dataSource=self;
    _listView.delegate=self;
    [self createHeaderView];
}

-(void)createHeaderView
{
    
    CGFloat w = (ScreenWidth - 40)/2;
    CGFloat h = w * 3 / 16.0 ;
    
    UIView *headerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 326 + 2 * h)];
    UIView *firstView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 148)];
    
    firstView.backgroundColor=[YZMAppStyle colorForMain];
    UIView *line1=[YZMAppStyle splitLine];
    line1.backgroundColor=[YZMAppStyle colorForSplitLine];
    [firstView addSubview:line1];
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(firstView);
        make.width.mas_equalTo(firstView.mas_width);
        make.centerX.equalTo(firstView);
    }];
    UILabel *nameLabel=[YZMAppStyle labelWithWhite];
    nameLabel.text=@"持仓盈亏（元）";
    [firstView addSubview:nameLabel];
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(firstView).offset(28);
        make.centerX.equalTo(firstView);

    }];
    
    myMoneyLabel=[YZMAppStyle labelWithGigWhite];
    myMoneyLabel.text=@"--";
    [firstView addSubview:myMoneyLabel];
    [myMoneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(nameLabel.mas_bottom).offset(14);
        make.centerX.equalTo(firstView);
    }];
    
    timeLabel=[YZMAppStyle labelWithMediumWhite];
    NSString *dayNumber=@"0";
    NSString *String=[NSString stringWithFormat:@"剩余操盘天数：%@天",dayNumber];
    NSMutableAttributedString *textstring=[[NSMutableAttributedString alloc]initWithString:String];
    [textstring addAttribute:NSForegroundColorAttributeName value:[YZMAppStyle colorForRiseText] range:NSMakeRange(7, dayNumber.length)];
    timeLabel.attributedText=textstring;
    [firstView addSubview:timeLabel];
    [timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(myMoneyLabel.mas_bottom).offset(8);
        make.centerX.equalTo(firstView);
    }];
    
    UIView *line2=[YZMAppStyle splitLine];
    line2.backgroundColor=[YZMAppStyle colorForSplitLine];
    [firstView addSubview:line2];
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(firstView);
        make.width.mas_equalTo(firstView.mas_width);
    }];
    
    UIView *secondView=[[UIView alloc]initWithFrame:CGRectMake(0, 148, ScreenWidth, 148)];
    secondView.backgroundColor=[YZMAppStyle colorForMain];
    
    UIView *line3=[YZMAppStyle splitLine];
    line3.backgroundColor=[YZMAppStyle colorForSplitLine];
    [secondView addSubview:line3];
    [line3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(secondView).offset(73);
        make.left.mas_equalTo(secondView);
        make.width.mas_equalTo(secondView.mas_width);
    }];
    
    UIView *line4=[YZMAppStyle splitLine];
    line4.backgroundColor=[YZMAppStyle colorForSplitLine];
    [secondView addSubview:line4];
    [line4 mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(147);
    }];
    
    [line4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(secondView);
        make.left.mas_equalTo(secondView).offset((ScreenWidth-3)/3);
        make.width.mas_equalTo(0.5);
    }];
    
    UIView *line5=[YZMAppStyle splitLine];
    line5.backgroundColor=[YZMAppStyle colorForSplitLine];
    [secondView addSubview:line5];
    [line5 mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(147);
    }];
    
    [line5 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(secondView);
        make.right.mas_equalTo(secondView.mas_right).offset(-(ScreenWidth-3)/3);
        make.width.mas_equalTo(0.5);
    }];
    
    UILabel *allMoneyLabel=[YZMAppStyle labelWithSmallGray];
    allMoneyLabel.text=@"总点买金额(元)";
    [secondView addSubview:allMoneyLabel];
    allMoneyLabel.textAlignment=NSTextAlignmentCenter;
    [allMoneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(secondView).offset(20);
        make.left.mas_equalTo(secondView);
        make.width.mas_equalTo(ScreenWidth*0.33);
    }];
    
    allMoney=[YZMAppStyle labelWithMediumWhite];
    allMoney.text=@"0";
    [secondView addSubview:allMoney];
    allMoney.textAlignment=NSTextAlignmentCenter;
    [allMoney mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(allMoneyLabel).offset(20);
        make.centerX.equalTo(allMoneyLabel);
        make.width.mas_equalTo(ScreenWidth*0.33);
    }];
    
    UILabel *ensureMoneyLabel=[YZMAppStyle labelWithSmallGray];
    ensureMoneyLabel.text=@"履约保证金(元)";
    [secondView addSubview:ensureMoneyLabel];
    ensureMoneyLabel.textAlignment=NSTextAlignmentCenter;
    [ensureMoneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(allMoneyLabel);
        make.left.mas_equalTo(line4);
        make.width.mas_equalTo(ScreenWidth*0.33);
    }];
    
    ensureMoney=[YZMAppStyle labelWithMediumWhite];
    ensureMoney.text=@"0";
    [secondView addSubview:ensureMoney];
    ensureMoney.textAlignment=NSTextAlignmentCenter;
    [ensureMoney mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(allMoney);
        make.centerX.equalTo(ensureMoneyLabel);
        make.width.mas_equalTo(ScreenWidth*0.33);
    }];
    

    UILabel *deferMoneyLabel=[YZMAppStyle labelWithSmallGray];
    deferMoneyLabel.text=@"递延费(元)";
    [secondView addSubview:deferMoneyLabel];
    deferMoneyLabel.textAlignment=NSTextAlignmentCenter;
    [deferMoneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(allMoneyLabel);
        make.left.mas_equalTo(line5);
        make.width.mas_equalTo(ScreenWidth*0.33);
    }];
    
    deferMoney=[YZMAppStyle labelWithMediumWhite];
    deferMoney.text=@"0";
    [secondView addSubview:deferMoney];
    deferMoney.textAlignment=NSTextAlignmentCenter;
    [deferMoney mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(allMoney);
        make.centerX.equalTo(deferMoneyLabel);
        make.width.mas_equalTo(ScreenWidth*0.33);
    }];
    
    UILabel *togetherMoneyLabel=[YZMAppStyle labelWithSmallGray];
    togetherMoneyLabel.text=@"总交易综合费(元)";
    togetherMoneyLabel.adjustsFontSizeToFitWidth=YES;
    [secondView addSubview:togetherMoneyLabel];
    togetherMoneyLabel.textAlignment=NSTextAlignmentCenter;
    [togetherMoneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(allMoneyLabel);
        make.top.mas_equalTo(line3).offset(20);
        make.width.mas_equalTo(ScreenWidth*0.33);
    }];
    
    togetherMoney=[YZMAppStyle labelWithMediumWhite];
    togetherMoney.text=@"0";
    [secondView addSubview:togetherMoney];
    togetherMoney.textAlignment=NSTextAlignmentCenter;
    [togetherMoney mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(togetherMoneyLabel);
        make.top.mas_equalTo(togetherMoneyLabel).offset(20);
        make.width.mas_equalTo(ScreenWidth*0.33);
    }];
    
    UILabel *currentMoneyLabel=[YZMAppStyle labelWithSmallGray];
    currentMoneyLabel.text=@"当前市值(元)";
    [secondView addSubview:currentMoneyLabel];
    currentMoneyLabel.textAlignment=NSTextAlignmentCenter;
    [currentMoneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(ensureMoney);
        make.centerY.equalTo(togetherMoneyLabel);
        make.width.mas_equalTo(ScreenWidth*0.33);
    }];
    
    currentMoney=[YZMAppStyle labelWithMediumWhite];
    currentMoney.text=@"0";
    [secondView addSubview:currentMoney];
    currentMoney.textAlignment=NSTextAlignmentCenter;
    [currentMoney mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(ensureMoney);
        make.centerY.equalTo(togetherMoney);
        make.width.mas_equalTo(ScreenWidth*0.33);
    }];
    
    UILabel *haltMoneyLabel=[YZMAppStyle labelWithSmallGray];
    haltMoneyLabel.text=@"停牌市值(元)";
    [secondView addSubview:haltMoneyLabel];
    haltMoneyLabel.textAlignment=NSTextAlignmentCenter;
    [haltMoneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(deferMoney);
        make.centerY.equalTo(currentMoneyLabel);
        make.width.mas_equalTo(ScreenWidth*0.33);
    }];
    
    haltMoney=[YZMAppStyle labelWithMediumWhite];
    haltMoney.text=@"0";
    [secondView addSubview:haltMoney];
    haltMoney.textAlignment=NSTextAlignmentCenter;
    [haltMoney mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(haltMoneyLabel);
        make.centerY.equalTo(togetherMoney);
        make.width.mas_equalTo(ScreenWidth*0.33);
    }];
    
    [headerView addSubview:firstView];
    [headerView addSubview:secondView];
    _listView.tableHeaderView=headerView;
    
//    UIButton *firstButton=[YZMAppStyle regButton];
//    [headerView addSubview:firstButton];
//    firstButton.backgroundColor=[YZMAppStyle colorForYellowButton];
//    firstButton.layer.borderWidth = 0;
//    firstButton.layer.cornerRadius=0;
//    firstButton.tag=101;
//    firstButton.titleLabel.adjustsFontSizeToFitWidth=YES;
//    firstButton.titleLabel.font=[YZMAppStyle smallSizeFont];
//    [firstButton setTitleColor:[YZMAppStyle colorForMain] forState:UIControlStateNormal];
//    [firstButton setTitle:@"追加点买金" forState:UIControlStateNormal];
//    [firstButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(headerView).offset(12);
//        make.width.mas_equalTo((ScreenWidth-60)/4);
//        make.bottom.mas_equalTo(headerView.mas_bottom).offset(-15);
//    }];
//    [firstButton addTarget:self action:@selector(headeraction:) forControlEvents:UIControlEventTouchUpInside];
//
//    UIButton *secondbutton=[YZMAppStyle regButton];
//    [headerView addSubview:secondbutton];
//    secondbutton.backgroundColor=[YZMAppStyle colorForYellowButton];
//    secondbutton.layer.borderWidth = 0;
//    secondbutton.layer.cornerRadius=0;
//    secondbutton.tag=102;
//    secondbutton.titleLabel.font=[YZMAppStyle smallSizeFont];
//    secondbutton.titleLabel.adjustsFontSizeToFitWidth=YES;
//    [secondbutton setTitleColor:[YZMAppStyle colorForMain] forState:UIControlStateNormal];
//    [secondbutton setTitle:@"追加保证金" forState:UIControlStateNormal];
//    [secondbutton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(firstButton.mas_right).offset(12);
//        make.width.mas_equalTo((ScreenWidth-60)/4);
//        make.centerY.equalTo(firstButton);
//    }];
//    [secondbutton addTarget:self action:@selector(headeraction:) forControlEvents:UIControlEventTouchUpInside];
//
//    UIButton *thirdButton=[YZMAppStyle regButton];
//    [headerView addSubview:thirdButton];
//    thirdButton.backgroundColor=[YZMAppStyle colorForYellowButton];
//    thirdButton.layer.borderWidth = 0;
//    thirdButton.layer.cornerRadius=0;
//    thirdButton.tag=103;
//    thirdButton.titleLabel.font=[YZMAppStyle smallSizeFont];
//    thirdButton.titleLabel.adjustsFontSizeToFitWidth=YES;
//    [thirdButton setTitleColor:[YZMAppStyle colorForMain] forState:UIControlStateNormal];
//    [thirdButton setTitle:@"申请清算" forState:UIControlStateNormal];
//    [thirdButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(secondbutton.mas_right).offset(12);
//        make.width.mas_equalTo((ScreenWidth-60)/4);
//        make.centerY.equalTo(firstButton);
//    }];
//    [thirdButton addTarget:self action:@selector(headeraction:) forControlEvents:UIControlEventTouchUpInside];
//
//    UIButton *fouthButton=[YZMAppStyle regButton];
//    [headerView addSubview:fouthButton];
//    fouthButton.backgroundColor=[YZMAppStyle colorForYellowButton];
//    fouthButton.layer.borderWidth = 0;
//    fouthButton.layer.cornerRadius=0;
//    fouthButton.tag=104;
//    fouthButton.titleLabel.font=[YZMAppStyle smallSizeFont];
//    fouthButton.titleLabel.adjustsFontSizeToFitWidth=YES;
//    [fouthButton setTitleColor:[YZMAppStyle colorForMain] forState:UIControlStateNormal];
//    [fouthButton setTitle:@"期限延期" forState:UIControlStateNormal];
//    [fouthButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(thirdButton.mas_right).offset(12);
//        make.width.mas_equalTo((ScreenWidth-60)/4);
//        make.centerY.equalTo(firstButton);
//    }];
//    [fouthButton addTarget:self action:@selector(headeraction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton* firstButton = [self createBtn:101 title:@"追加点买金"];
    [headerView addSubview:firstButton];
    [firstButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(headerView).offset(12);
        make.width.mas_equalTo(w);
        make.top.equalTo(secondView.mas_bottom).offset(10);
        make.height.mas_equalTo(h);
    }];
    
    UIButton* secondbutton = [self createBtn:102 title:@"追加保证金"];
    [headerView addSubview:secondbutton];
    [secondbutton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(headerView).offset(-12);
        make.width.mas_equalTo(w);
        make.top.equalTo(secondView.mas_bottom).offset(10);
        make.height.mas_equalTo(h);
    }];
    
    UIButton* thirdButton = [self createBtn:103 title:@"申请清算"];
    [headerView addSubview:thirdButton];
    [thirdButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(headerView).offset(12);
        make.width.mas_equalTo(w);
        make.top.equalTo(firstButton.mas_bottom).offset(10);
        make.height.mas_equalTo(h);
    }];
    
    UIButton* fouthButton = [self createBtn:104 title:@"期限续期"];
    [headerView addSubview:fouthButton];
    [fouthButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(headerView).offset(-12);
        make.width.mas_equalTo(w);
        make.top.equalTo(firstButton.mas_bottom).offset(10);
        make.height.mas_equalTo(h);
    }];
}

- (UIButton *)createBtn:(NSUInteger)tag  title:(NSString *)title{
    
    UIButton* firstButton = [UIButton buttonWithType:UIButtonTypeCustom];
    firstButton.backgroundColor = [YZMAppStyle colorForMain];
    firstButton.tag = tag;
//    firstButton.titleLabel.adjustsFontSizeToFitWidth=YES;
    firstButton.titleLabel.font=[YZMAppStyle largeSizeFont];
    [firstButton setTitleColor:[YZMAppStyle colorForYellowButton] forState:UIControlStateNormal];
    [firstButton setTitle:title forState:UIControlStateNormal];
    [firstButton addTarget:self action:@selector(headeraction:) forControlEvents:UIControlEventTouchUpInside];
    [YZMSetBorderAndCornerRadius setView:firstButton borderWidth:1 borderColor:[YZMAppStyle colorForYellowButton] cornerRadius:5];
    
    return firstButton;
}


-(void)headeraction:(UIButton *)sender
{
    if (!self.model) {
        
        return;
    }
    WS(ws)
    switch (sender.tag) {
        case 101:{
            [YZMDelayCharge showDelayChargeViewWithConfirmHandle:^BOOL{
                [ws addMoneyMethod];
                return YES;
            } cancleHandle:nil noWaitPayHandle:^{
                [ws addMoneyMethod];
            }];
            
        }
            break;
        case 102:
        {
            [YZMDelayCharge showDelayChargeViewWithConfirmHandle:^BOOL{
                [ws addBoundMoneyMethod];
                return YES;
            } cancleHandle:nil noWaitPayHandle:^{
               [ws addBoundMoneyMethod];
            }];
        }
            break;
        case 103:
        {
            [self applySattleMethod];
        }
            break;
        case 104:{
             [self dateDelayMethod];
         }
    
            break;
        default:
            break;
    }
}

//追加点买金
- (void)addMoneyMethod{
    WS(ws);
    YZMAlertView *alertView=[YZMAlertView alertwithtitle:@"追加点买金额" withfirststring:@"追加点买金额:" firstvalue:@(self.addMoney / 10000) secondstring:@"支付履约保证金:" secondvalue:@(floor(self.addMoney / self.model.leverRatio)) thirdstring:@"递延费:" thirdvalue:@(floor(self.addMoney / 10000 * self.service.defaultConfigure.deferCharge * self.model.availableDays))];
    alertView.tag = 1000;
    alertView.addmoneyTextfield.delegate = self;
    alertView.addmoneyTextfield.tag = 1001;
    __weak YZMAlertView *_alertView = alertView;
    alertView.confirmHandle=^(){
        
        if ([ws textFieldShouldEndEditing:_alertView.addmoneyTextfield]) {
            
            self.addMoneyFlag = YES;
            return YES;
        }
        
        self.addMoneyFlag = NO;
        return NO;
    };
    NSInteger maxMoney = [[self.service.defaultConfigure.tradingMoneyList lastObject] money] - self.model.money;
    if (![@(maxMoney) isGreaterThanDouble:0]) {
        
        NSString *hintStr = [NSString stringWithFormat:@"总点买金额不得超过%@", @(self.model.money)];
        [MBProgressHUD showMessage:hintStr];
        return;
    }
    
    //追加点买金初始化
    [self fecthAddMoneyInit:alertView];
    
    [alertView showInView:self.navigationController.view];
}

//追加保证金
- (void)addBoundMoneyMethod{
    WS(ws);
    double bondsRatio = (self.model.marketValue + self.model.availableMoney) / self.model.money * 100;
    self.bonds = 0;
    if (![@(bondsRatio) isGreaterThanDouble:self.service.defaultConfigure.deferConditionRatio + 1]) {
        
        self.bonds = self.model.money * ((self.service.defaultConfigure.deferConditionRatio + 1 - bondsRatio) / 100);
    }
    YZMAlertView *alertview = [YZMAlertView addBondsAlertWithTitle:@"追加履约保证金" withFirstString:@"当前市值:" firstValue:@(self.model.marketValue) secondString:@"可用余额:" secondValue:@(self.model.availableMoney) thirdString:@"追加履约保证金:" thirdValue:@(self.bonds)];
    alertview.addmoneyTextfield.delegate = self;
    alertview.addmoneyTextfield.tag = 1002;
    __weak YZMAlertView *_alertView = alertview;
    alertview.confirmHandle=^(){
        
        if ([ws textFieldShouldEndEditing:_alertView.addmoneyTextfield]) {
            
            //追加履约保证金
            [ws addBondsMoney];
            return YES;
        }
        
        return NO;
    };
    [alertview showInView:self.navigationController.view];
}

//申请清算
- (void)applySattleMethod{
    WS(ws);
    YZMAlertView *alertview=[YZMAlertView alertViewForClearAll];
    
    alertview.confirmHandle=^(){
        
        //申请清算
        [ws applySettlement];
        return YES;
    };
    [alertview showInView:self.navigationController.view];
}

//期限延期
- (void)dateDelayMethod{
    WS(ws);
    if (self.model.availableDays > 2) {

        YZMAlertView *alertView = [[YZMAlertView alloc] init];
        alertView.contentLabel.text = @"策略组到期前3天才能续期";
        alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
        alertView.cancelButton.hidden = YES;
        [alertView showInView:self.navigationController.view];

        return;
    }

    [YZMDelayCharge showDelayChargeViewWithConfirmHandle:^BOOL{
        [ws dateDelayMoney];
        return YES;
    } cancleHandle:nil noWaitPayHandle:^{
        [ws dateDelayMoney];
        
    }];
    
}

- (void)dateDelayMoney{
    WS(ws);
    double  deferCharge =  self.model.money * self.service.defaultConfigure.deferCharge * [self.service.defaultConfigure.holdDayList[0] integerValue] / 10000;
    changeDeferalertview = [YZMAlertView alertViewForChangeDeferWithFristValue:@(self.model.money) withSecondValue:@(floor(self.model.money / self.service.defaultConfigure.leverValue)) withFouthValue:@(deferCharge) withHoldDay:self.service.defaultConfigure.holdDayList[0] withHint:@""];
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(choiceway:)];
    [changeDeferalertview.deferTimeLabel addGestureRecognizer:tap];
   
    changeDeferalertview.tag = 1003;
//    changeDeferalertview.cancelButton
    __weak YZMAlertView *_alertView = changeDeferalertview;
    changeDeferalertview.confirmHandle=^(){
        
        //方案续期
        [ws addSchemeRenewal:_alertView];
        
        return YES;
    };
    
    //追加点买金初始化
    [self fecthRenewalInit:changeDeferalertview];
    
    [changeDeferalertview showInView:self.navigationController.view];
}


#pragma mark -- Network

- (void)addSchemeRenewal:(YZMAlertView *)alertView {
    
    /*无网处理*/
    if (kNetworkNotReachability) {
        
        [NSError yz_showMessageForNoWifi];
    }
    
    double balance = fabs(self.diffBalance) - YZMUserServiceInstance.user.assets.balance;
    
    if ([@(balance) isGreaterThanDouble:0]) {
        
        [self alertBalance:balance];
        
        return;
    }
    
    double deferCharge =  self.model.money * self.service.defaultConfigure.deferCharge * [[alertView.deferTimeLabel.text stringByReplacingOccurrencesOfString:@"天" withString:@""] integerValue] / 10000;
    [YZClient td_addSchemeRenewalInitWithParams:@{@"id":@(self.model.Id),
                                                  @"holdDays":[alertView.deferTimeLabel.text stringByReplacingOccurrencesOfString:@"天" withString:@""],
                                                  @"lossPrincipal":@(floor(self.model.money / self.service.defaultConfigure.leverValue)),
                                                  @"diffBalance":@(self.diffBalance),
                                                  @"deferCharge":@(deferCharge).r2fString} success:^(NSURLSessionDataTask *task, id responseObject) {
        
        YZGeneralResultModel *topModel=responseObject;
        if (topModel.success) {
            
            [YZMUserServiceInstance fetchUserAssetsInfo];
            [MBProgressHUD showMessage:@"策略组续期成功"];
            
            //刷新页面
            [self getinformation];
        }
        else{
            
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        
        [error yz_showMessage];
    }];
}

- (void)fecthRenewalInit:(YZMAlertView *)alertView {
    
    /*无网处理*/
    if (kNetworkNotReachability) {
        
        [NSError yz_showMessageForNoWifi];
    }
    
    [YZClient td_fetchRenewalInitWithParams:@{@"id":@(self.model.Id), @"holdDays":[alertView.deferTimeLabel.text stringByReplacingOccurrencesOfString:@"天" withString:@""]} success:^(NSURLSessionDataTask *task, id responseObject) {
        
        YZGeneralResultModel *topModel=responseObject;
        if (topModel.success) {
            
            alertView.hintLabel.hidden = NO;
            double money = [topModel.data doubleValue];
            if ([@(money) isGreaterThanDouble:0]) {
                
                alertView.hintLabel.text = [NSString stringWithFormat:@"续期需要履约保证金%@元,退回%@元", @(floor(self.model.money / self.service.defaultConfigure.leverValue)).r2fString, @(money).r2fString];
            } else if ([@(money) isEqualWithDouble:0]) {
                
                alertView.hintLabel.hidden = YES;
            } else {
                
                NSString *lessMoney = [ @(money).r2fString stringByReplacingOccurrencesOfString:@"-" withString:@""];
                alertView.hintLabel.text = [NSString stringWithFormat:@"续期需要履约保证金%@元,补交%@元", @(floor(self.model.money / self.service.defaultConfigure.leverValue)).r2fString, lessMoney];
                self.diffBalance = money;
            }
        }
        else{
            
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        
        [error yz_showMessage];
    }];
}

- (void)addBondsMoney {
    
    /*无网处理*/
    if (kNetworkNotReachability) {
        
        [NSError yz_showMessageForNoWifi];
    }
    
    double balance = self.bonds - YZMUserServiceInstance.user.assets.balance;
    
    if ([@(balance) isGreaterThanDouble:0]) {
        
        [self alertBalance:balance];
        
        return;
    }
    
    [YZClient td_addBondsMoneyWithParams:@{@"id":@(self.model.Id), @"lossPrincipal":@(self.bonds).p2fString} success:^(NSURLSessionDataTask *task, id responseObject) {
        
        YZGeneralResultModel *topModel=responseObject;
        if (topModel.success) {
            
            [YZMUserServiceInstance fetchUserAssetsInfo];
            [MBProgressHUD showMessage:@"追加履约保证金成功"];
            
            //刷新页面
            [self getinformation];
        }
        else{
            
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        
        [error yz_showMessage];
    }];
}

- (void)applySettlement {
    
    /*无网处理*/
    if (kNetworkNotReachability) {
        
        [NSError yz_showMessageForNoWifi];
    }
    
    [YZClient td_applySettlementWithParams:@{@"id":@(self.model.Id)} success:^(NSURLSessionDataTask *task, id responseObject) {
        
        YZGeneralResultModel *topModel=responseObject;
        if (topModel.success) {
            
            [YZMUserServiceInstance fetchUserAssetsInfo];
            [MBProgressHUD showMessage:@"申请结算策略组成功"];
            
            //刷新页面
            [self getinformation];
        }
        else{

            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        
        [error yz_showMessage];
    }];
}

- (void)confirmAddBuyMoney:(YZMAlertView *)alertView {
    
    /*无网处理*/
    if (kNetworkNotReachability) {
        
        [NSError yz_showMessageForNoWifi];
    }
    
    double balance = ([alertView.bondLabel.text doubleValue] + [alertView.deferLabel.text doubleValue]) - YZMUserServiceInstance.user.assets.balance;
    
    if ([@(balance) isGreaterThanDouble:0]) {
        
        [self alertBalance:balance];
        
        return;
    }
    
    [YZClient td_confirmAddMoneyWithParams:@{@"id":@(self.model.Id), @"money":@([alertView.addmoneyTextfield.text doubleValue] * 10000), @"lossPrincipal":alertView.bondLabel.text, @"deferCharge":alertView.deferLabel.text} success:^(NSURLSessionDataTask *task, id responseObject) {
        
        YZGeneralResultModel *topModel=responseObject;
        if (topModel.success) {
            
            self.addMoneyFlag = NO;
            [YZMUserServiceInstance fetchUserAssetsInfo];
            [MBProgressHUD showMessage:@"追加总点买金额成功"];
            //刷新页面
            [self getinformation];
        }
        else{
            
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        
        [error yz_showMessage];
    }];
}

- (void)fecthAddMoneyInit:(YZMAlertView *)alertView {
    
    /*无网处理*/
    if (kNetworkNotReachability) {
        
        [NSError yz_showMessageForNoWifi];
    }
    
    [YZClient td_fetchAddMoneyInitWithParams:@{@"id":@(self.model.Id), @"money":@(self.addMoney)} success:^(NSURLSessionDataTask *task, id responseObject) {
        
        YZGeneralResultModel *topModel=responseObject;
        
        if (topModel.success) {
            
            alertView.bondLabel.text = [NSString stringWithFormat:@"%@", @(floor(self.addMoney / self.model.leverRatio))];
            NSNumber *deferCharge = topModel.data;
            alertView.deferLabel.text = deferCharge.rfString;
            
            if (self.addMoneyFlag) {
                
                //确认追加点买金
                [self confirmAddBuyMoney:alertView];
            }
        }
        else{
            
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        
        [error yz_showMessage];
    }];
}

-(void)getinformation
{
    /*无网处理*/
    if (kNetworkNotReachability) {
        
        [NSError yz_showMessageForNoWifi];
    }
    
    [YZClient getmystategy:^(NSURLSessionDataTask *task, id responseObject) {
        YZGeneralResultModel *topModel=responseObject;
        if (topModel.success) {
            
            YZMMyStackModel *myModel=topModel.data;
            if (myModel) {
                NSInteger schemeId= myModel.Id;
                [[NSUserDefaults standardUserDefaults]setObject:@(schemeId) forKey:@"schemeId"];
                if (myModel.currentProfit) {
                    myMoneyLabel.text=[NSString stringWithFormat:@"%@",@([myModel.currentProfit doubleValue]).r2fString];
                    if ([@([myModel.currentProfit doubleValue]) isGreaterThanDouble:0]) {
                        myMoneyLabel.text=[NSString stringWithFormat:@"+%@",@([myModel.currentProfit doubleValue]).r2fString];
                        myMoneyLabel.textColor=[YZMAppStyle colorForRiseText];
                    }else if (![@([myModel.currentProfit doubleValue]) isEqualGreaterThanDouble:0]) {
                        
                        myMoneyLabel.textColor=[YZMAppStyle colorForDropText];
                    }else if ([@([myModel.currentProfit doubleValue]) isEqualWithDouble:0]){
                        
                        myMoneyLabel.textColor=[YZMAppStyle colorForWhite];
                        myMoneyLabel.text=@"--";
                    }
                }
                
                NSString *dayNumber=[NSString stringWithFormat:@"%@",@(myModel.availableDays)];
                NSString *String=[NSString stringWithFormat:@"剩余操盘天数:%@天",dayNumber];
                NSMutableAttributedString *textstring=[[NSMutableAttributedString alloc]initWithString:String];
                [textstring addAttribute:NSForegroundColorAttributeName value:[YZMAppStyle colorForRiseText] range:NSMakeRange(7, dayNumber.length)];
                timeLabel.attributedText=textstring;
                allMoney.text=[NSString stringWithFormat:@"%@",@(myModel.money).r2fString];
                ensureMoney.text=[NSString stringWithFormat:@"%@",@(myModel.lossPrincipal).r2fString];
                deferMoney.text=[NSString stringWithFormat:@"%@",@(myModel.deferCharge).r2fString];
                togetherMoney.text=[NSString stringWithFormat:@"%@",@(myModel.serviceCharge).r2fString];
                currentMoney.text=[NSString stringWithFormat:@"%@",@(myModel.marketValue).r2fString];
                haltMoney.text=[NSString stringWithFormat:@"%@",@(myModel.suspendedValue).r2fString];
                
                self.model = myModel;
            }
        }
        else{
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        [error yz_showMessage];
    }];
}

- (void)alertBalance:(double)money {

    //余额不足
    YZMAlertView *alertView = [[YZMAlertView alloc] initWithFrame:self.view.frame];
    alertView.titleLabel.text = @"余额不足";
    alertView.titleLabel.textAlignment = NSTextAlignmentLeft;
    alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
    [alertView.sureButton setTitle:@"马上充值" forState:UIControlStateNormal];
    [alertView.cancelButton setTitle:@"暂不充值" forState:UIControlStateNormal];
    alertView.confirmHandle = ^{
        
        [YZMHCMInstance pushViewControllerWithName:@"recharge" andParams:@{YZBACKFLAG:@(YES)}];
        return YES;
    };

    NSString *attStr = [NSString stringWithFormat:@"您的账户余额为%@元,本次付款还差%@元!", @(YZMUserServiceInstance.user.assets.balance).decimalP02fString, @(money).r2fString];
    NSMutableAttributedString *detailAttStr = [[NSMutableAttributedString alloc] initWithString:attStr];
    
    NSUInteger len = [attStr rangeOfString:@","].location - [attStr rangeOfString:@"为"].location - 2;
    [detailAttStr addAttribute:NSForegroundColorAttributeName value:[YZMAppStyle colorForRiseText] range:NSMakeRange([attStr rangeOfString:@"为"].location + 1,len)];
    alertView.contentLabel.attributedText = detailAttStr;

    [alertView showInView:self.navigationController.view];
}

#pragma mark -- UITextFieldDelegate

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    
    if (textField.tag == 1001) {
        
        NSInteger minMoney = 1;
        NSInteger maxMoney = ([[self.service.defaultConfigure.tradingMoneyList lastObject] money] - self.model.money) / 10000;
        NSNumber *currentBuyMoney = @([textField.text integerValue]);
        YZMAlertView *alertView = [self.navigationController.view viewWithTag:1000];
        
        if ([currentBuyMoney isGreaterThanDouble: maxMoney]) {
            
            textField.text = [NSString stringWithFormat:@"%@", @(maxMoney).r2fString];
            self.addMoney = maxMoney * 10000;
            
            if (maxMoney != 0) {
                
                [self fecthAddMoneyInit:alertView];
                return NO;
            } else {
                
                return YES;
            }
            
        } else if (![currentBuyMoney isEqualGreaterThanDouble: minMoney]) {
            
            textField.text = [NSString stringWithFormat:@"%@", @(minMoney).r2fString];
            self.addMoney = minMoney * 10000;
            
            [self fecthAddMoneyInit:alertView];
            return NO;
        } else {
            
            textField.text = [NSString stringWithFormat:@"%@", currentBuyMoney];
            self.addMoney = [currentBuyMoney integerValue] * 10000;
            
            if (maxMoney != 0) {
                
                [self fecthAddMoneyInit:alertView];
            }
            
            return YES;
        }
    }
    
    if (textField.tag == 1002) {
        
        double minMoney = self.bonds;
        NSNumber *currentBuyMoney = @([textField.text doubleValue]);
        
        if (![currentBuyMoney isEqualGreaterThanDouble: minMoney]) {
            
            [MBProgressHUD showMessage:[NSString stringWithFormat:@"履约保证金不能小于%@", @(minMoney).r2fString]];
            textField.text = [NSString stringWithFormat:@"%@", @(minMoney).r2fString];
            self.bonds = minMoney;
            
            return NO;
        } else {
            
            textField.text = [NSString stringWithFormat:@"%@", currentBuyMoney.r2fString];
            self.bonds = [currentBuyMoney doubleValue];
        }
    }
    
    return YES;
}

#pragma mrak -- event

-(void)choiceway:(UITapGestureRecognizer *)sender
{
    if (!popView) {
        popView = [[XYPopView alloc] initWithSuperView:sender.view items:self.service.defaultConfigure.holdDayList];
        popView.PopBorderColor=[YZMAppStyle colorForGrayUnable];
        popView.delegate = self;
    }
    __weak XYPopView* pop = popView;
    changeDeferalertview.cancleHandle = ^{
        [pop hiddenPopView];
    };
    changeDeferalertview.confirmHandle = ^BOOL{
        [pop hiddenPopView];
        return YES;
    };
    [popView showPopView];
}

- (void)chooseButton:(NSString *)title
{
    changeDeferalertview.deferTimeLabel.text = [NSString stringWithFormat:@"%@天", title];
    
    YZMAlertView *alertView = [self.navigationController.view viewWithTag:1003];
     double deferCharge =  self.model.money * self.service.defaultConfigure.deferCharge * [[alertView.deferTimeLabel.text stringByReplacingOccurrencesOfString:@"天" withString:@""] integerValue] / 10000;
    alertView.deferLabel.text = [NSString stringWithFormat:@"%@", @(deferCharge).r2fString];
    //追加点买金初始化
    [self fecthRenewalInit:alertView];
}

#pragma mark --tableview

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _datasource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YZMSeparatorCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    YZMIndexCount indexCount;
    indexCount.index = indexPath.row;
    indexCount.count = _datasource.count;
    cell.indexCount = indexCount;
    cell.leftMargin = 10;
    cell.rightMargin = 10;
    
    cell.textLabel.text=[_datasource[indexPath.row]objectForKey:@"titleName"];
    cell.backgroundColor=[YZMAppStyle colorForMain];
    cell.textLabel.textColor=[YZMAppStyle colorForMainTextColor];
    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.textLabel.font=[YZMAppStyle mediumSizeFont];
    [cell.contentView insertSubview:cell.textLabel belowSubview:cell.bottomLineView];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    NSString *pageName=[self.datasource[indexPath.row]objectForKey:YZNEXTPAGE];
    NSDictionary *params = nil;
    if ([pageName isEqualToString:@"currentthing"]) {
        [YZMHCMInstance pushViewControllerWithName:@"stockTD" andParams:@{@"segment":@(1)}];
    } else if ([pageName isEqualToString:@"balance"]) {
        
        [YZMHCMInstance pushViewControllerWithName:@"stockTD" andParams:@{@"segment":@(2)}];
    } else {
        
        [YZMCMInstance pushByCheckingAuthWithName:pageName andParams:params];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
